<template>
  <div>
    <h1>{{ id ? "编辑" : "新建" }}班次</h1>
    <el-form label-width="120px" @submit.native.prevent="save">
      <el-form-item label="名称">
        <el-input v-model="model.name"></el-input>
      </el-form-item>
      <el-form-item label="起点">
        <el-cascader
          size="large"
          :options="options"
          v-model="selectedOptions_start"
          @change="handleChange1"
        >
        </el-cascader>
      </el-form-item>
      <el-form-item label="终点">
        <el-cascader
          size="large"
          :options="options"
          v-model="selectedOptions_end"
          @change="handleChange2"
        >
        </el-cascader>
      </el-form-item>
      <el-form-item label="票数">
        <el-input-number
          v-model="model.left"
          :min="1"
          :max="60"
          label="票数"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="价格">
        <el-input-number
          v-model="model.money"
          :min="1"
          :max="800"
          label="价格"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="出发时间">
        <el-date-picker
          v-model="model.start_date"
          type="datetime"
          placeholder="选择日期"
          >>
        </el-date-picker>
      </el-form-item>
      <el-form-item label="到达时间">
        <el-date-picker
          v-model="model.end_date"
          type="datetime"
          placeholder="选择日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="出发日期">
        <el-input v-model="model.start_date_simple"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { provinceAndCityData,CodeToText } from 'element-china-area-data'
export default {
  props: {
    id: {}
  },
  data() {
    return {
      model: {},
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
      },
      options: provinceAndCityData,
      selectedOptions_start: [],
      selectedOptions_end: [],
    }
  },
  methods: {
    async save() {
      let res
      if (this.id) {
        res = await this.$http.put(`rest/flights/${this.id}`, this.model)
      } else {
        res = await this.$http.post('rest/flights', this.model)
      }

      this.$router.push('/flights/list')
      this.$message({
        type: 'success',
        message: '保存成功'
      })
    },
    async fetch() {
      const res = await this.$http.get(`rest/flights/${this.id}`)
      this.model = res.data
    },
    handleChange1(value) {
      this.model.start_position = CodeToText[value[1]]
    },
    handleChange2(value) {
      this.model.end_position = CodeToText[value[1]]
    }
  },

  created() {
    this.id && this.fetch()
  }
}
</script>

